﻿using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace zijian666.Data
{
    /// <summary>
    /// 控制日志输出
    /// </summary>
    public static class Diagnostic
    {
        static readonly DiagnosticListener _listener = new DiagnosticListener(Assembly.GetExecutingAssembly().GetName().Name);

        /// <summary>
        /// 是否启用日志
        /// </summary>
        public static bool IsEnabled => _listener.IsEnabled() || IsDebug;

        /// <summary>
        /// 是否启用调试模式(在日志禁用时将日志输出到控制台)
        /// </summary>
        public static bool IsDebug { get; set; } = Debugger.IsAttached;

        /// <summary>
        /// 写日志
        /// </summary>
        public static void Wirte(string name
            , Func<string> getContent
            , [CallerFilePath] string file = null
            , [CallerMemberName] string member = null
            , [CallerLineNumber] int line = 0)
        {
            if (!_listener.IsEnabled())
            {
                if (IsDebug)
                {
                    Console.WriteLine(_listener.Name + " => " + new DiagnosticData(name, getContent(), null, file, member, line));
                }
                return;
            }
            _listener.Write(name, new DiagnosticData(name, getContent(), null, file, member, line));
        }


        /// <summary>
        /// 写日志
        /// </summary>
        public static void Wirte(string name
            , string content
            , [CallerFilePath] string file = null
            , [CallerMemberName] string member = null
            , [CallerLineNumber] int line = 0)
        {
            if (!_listener.IsEnabled())
            {
                if (IsDebug)
                {
                    Console.WriteLine(_listener.Name + " => " + new DiagnosticData(name, content, null, file, member, line));
                }
                return;
            }
            _listener.Write(name, new DiagnosticData(name, content, null, file, member, line));
        }

        /// <summary>
        /// 写日志
        /// </summary>
        public static void Error(Exception exception
            , [CallerFilePath] string file = null
            , [CallerMemberName] string member = null
            , [CallerLineNumber] int line = 0)
        {
            if (!_listener.IsEnabled())
            {
                if (IsDebug)
                {
                    Console.WriteLine(_listener.Name + " => " + new DiagnosticData(member, exception.Message, exception, file, member, line));
                }
                return;
            }
            _listener.Write("Error", new DiagnosticData(member, exception.Message, exception, file, member, line));
        }
    }
}
